package ysm.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import ysm.entity.User;
import ysm.mapper.UserMapper;


@Service
public class UserService implements UserDetailsService{
	
	@Autowired
	private UserMapper userMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		User user = userMapper.loadUserByUsername(username);
		System.out.println(user.getPassword());
		if (user == null) {
			throw new UsernameNotFoundException("账户不存在！");
		}
		user.setRoles(userMapper.getUserRolesByUid(user.getId()));
		return user;
	}

	public boolean addUser(User user) {
		// TODO Auto-generated method stub
		if (userMapper.loadUserByUsername(user.getUsername()) == null) {
			BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
			String hashedPassword = passwordEncoder.encode(user.getPassword());
			user.setPassword(hashedPassword);
			userMapper.addUser(user);
			return true;
		} else {
			return false;
		}
		
	}

	public void updateUsernameByUsername(String oldUsername, String newUsername) {
		// TODO Auto-generated method stub
		userMapper.updateUsernameByUsername(oldUsername, newUsername);
	}

}
